<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use Crypt;
use DB;
    
class LoginController extends Controller
{
    //login
    public function login()
    {
    	return view('admin.login.login');
    }

    //doLogin
    public function doLogin(Request $request)
    {

        // dd($request -> all());

    	$this -> validate($request,[
    		'account' => 'required',
    		'password' => 'required',
    		'code' => 'required'
    		],[
    		'account.required' => '账号不能为空',
    		'password.required' => '密码不能为空',
    		'code.required' => '验证码不能为空'
    	]);

        //声明ID
        $id = '';

    	//验证码是否正确
    	if($request -> input('code') == session('milkcaptcha'))
    	{

    		$res = DB::table('admin')
                 -> where('email', $request -> input('account') )
                 -> orWhere('username',$request -> input('account'))
                 -> first();
            if(!$res)
            {
               return back() -> with(['error' => '用户不存在']); 
            }

            if($res -> status == '0')
            {
                return back() -> with(['error' => '用户已冻结']);
            }

            $id = $res -> id;
                 // dd($id);
    		$password = Crypt::decrypt($res -> password);

    		if($request -> input('password') == $password)
    		{   
                $data = $request -> except('_token','code','account','password');
                $time = date('Y-m-d H:i:s');
                $data['last_time'] = $time;
                
               // dd($data);
                DB::table('admin')
                 -> where('id',$id)
                 -> update($data);

    			session(['master' => $res]);


    			return redirect('/admin/index/index');
    		}
    	}else
    	{
    		return back() -> with(['error' => '验证码错误']);
    	}
    }

    //logout
    public function logout()
    {
    	session() -> flush();
    	return redirect('/admin/login');
    }
}
